package designpatterns.structure;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理（运行期利用JVM的反射机制生成代理类,这里是直接生成类的字节码，然后通过类加载器载入JAVA虚拟机执行）
 * 使用场景：增强具体业务、添加log，重试，统一权限判断
 *
 * @author jack.wu
 * @since 2019/9/19
 */
public class DynamicProxyTest {

    public static void main(String[] args) {
        Person person = new Student();
        MyInvocationHandler handler = new MyInvocationHandler(person);
        Person proxy = (Person)Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(), handler);
        proxy.sayHello("123");
    }
}

interface Person {
    void sayHello(String context);
}

class Student implements Person {

    @Override
    public void sayHello(String context) {
        System.out.println("Student Say :" + context);
    }
}

class MyInvocationHandler implements InvocationHandler {

    private Person person;

    protected MyInvocationHandler(Person person) {
        this.person = person;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // begin something
        System.out.println("MyInvocationHandler invoke begin");
        System.out.println("proxy:" + proxy.getClass().getName());
        System.out.println("method:" + method.getName());
        for (Object o : args) {
            System.out.println("arg:" + o);
        }
        method.invoke(person,args);
        // end something
        System.out.println("MyInvocationHandler invoke end");
        return null;
    }
}

